import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import router from "@/router";
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: "http://43.137.62.10:8081/",
  baseURL: "http://192.168.1.2:8081/",
  timeout: 120000, // request timeout`
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["Authorization"] = getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    if (res.code === 401) {
      sessionStorage.removeItem("token");
      router.replace({ name: "Login" });
      Message({
        message: "登录失效，请重新登录！",
        type: "warning",
        duration: 5 * 1000,
      });
    } else if (res.code === 500) {
      Message({
        message: res.msg || "请输入必传参数",
        type: "error",
      });
      return "error";
    } else {
      return res;
    }
  },
  (error) => {
    // Message({
    //   message: error.msg,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // return Promise.reject(error)
    return error;
  }
);

export default service;
